import request from '@/utils/request.js'

// 用户认证
export const userRegisterService = (data) => {
    return request.post('/api/user/register', data)
}

export const userLoginService = async (data) => {
    try {
        console.log('Attempting login with data:', data)
        const response = await request.post('/api/user/login', data)
        
        // 验证返回数据格式
        if (!response.data?.token) {
            console.error('Invalid login response:', response)
            throw new Error('登录响应缺少token字段')
        }

        console.log('Login successful, token received')
        return {
            ...response,
            data: {
                token: response.data.token,
                ...response.data
            }
        }
    } catch (error) {
        console.error('Login failed:', error)
        throw error
    }
}

// 用户信息
export const userInfoService = () => {
    return request.get('/api/user/userInfo')
}

export const userUpdateService = (data) => {
    return request.put('/api/user/update', data)
}

export const userUpdateInfoService = (data) => {
    return request.put('/api/user/updateInfo', data)
}

export const userUpdateAvatarService = (data) => {
    return request.patch('/api/user/updateAvatar', data)
}

export const userUpdatePwdService = (data) => {
    return request.patch('/api/user/updatePwd', data)
}

// 文件上传
export const uploadFileService = (file) => {
    const formData = new FormData()
    formData.append('file', file)
    return request.post('/api/upload', formData, {
        headers: {
            'Content-Type': 'multipart/form-data'
        }
    })
}

// 用户管理
export const userListService = (params) => {
    return request.post('/api/user/list', params)
}

export const userStatusUpdateService = (data) => {
    return request.patch('/api/user/status', data)
}

export const userRoleUpdateService = (data) => {
    return request.patch('/api/user/role', data)
}

export const userDeleteService = (id) => {
    return request.delete(`/api/user/${id}`)
}